<?php
	class ModelMessageMessage extends Model {
		public function addMessage($data) {
			$sql = "INSERT INTO message_board SET muser_id = '".$this->db->escape($data['user_id'])."',";
			if(isset($data['mrid'])) {
				$sql.="mrid = '".$this->db->escape($data['mrid'])."',";
			}
			if(isset($data['ruser_id'])) {
				$sql.="ruser_id = '".$this->db->escape($data['ruser_id'])."',";
			}
			$sql.=" type = '".$this->db->escape($data['type'])."',send_time = NOW(),content = '".$this->db->escape($data['content'])."'";
			$row = $this->db->query($sql);
			return $this->db->getLastId();
		}
		public function getMessages($data) {
			$sql = "SELECT u.nickname,m.*,(SELECT nickname FROM user WHERE user_id = m.ruser_id) AS rnickname FROM message_board m LEFT JOIN user u ON (m.muser_id = u.user_id) ";
			if((int)$data['mrid'] ===0){
				$sql .="WHERE m.mrid = 0 ";
			}elseif((int)$data['mrid'] ===1){
				$sql .="WHERE m.mrid <> 0 ";
			}
			$sql .="ORDER BY m.send_time";
			if (isset($data['start']) || isset($data['limit'])) {
				if ($data['start'] < 0) {
					$data['start'] = 0;
				}

				if ($data['limit'] < 1) {
					$data['limit'] = 10;
				}

				$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
			}
			$query = $this->db->query($sql);
			return $query->rows;
		}
		public function totalMessages() {
			$query = $this->db->query("SELECT COUNT(*) AS total FROM message_board WHERE mrid = 0");
			return $query->row;
		}
	}